package com.cy.dda.web.front;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cy.dda.comm.constant.Constants;
import com.cy.dda.comm.utils.CommonUtils;
import com.cy.dda.comm.utils.ImageVerifyCodeUtils;
import com.cy.dda.model.Result;
import com.cy.dda.model.ao.sms.CheckImageCodeAO;
import com.cy.dda.model.ao.sms.SmsCodeAO;
import com.cy.dda.model.ao.user.UserLoginAO;
import com.cy.dda.model.ao.user.UserResetPasswordAO;
import com.cy.dda.model.enums.SmsType;
import com.cy.dda.service.comm.SmsService;
import com.cy.dda.service.user.UserService;
import com.cy.dda.web.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 前台-公用方法
 *
 * @author: tanyilin
 * @create: 2018年10月26日 下午2:39:45
 */
@Slf4j
@RestController
@RequestMapping("/home")
@Api(tags = "前台-公用方法")
public class HomeController extends BaseController{

	@Autowired
	private UserService userService;
	@Autowired
    private SmsService smsService;
	
	@ApiOperation("用户登录")
	@PostMapping("/user/login")
	public Result userLogin(@Validated UserLoginAO userLoginAO, BindingResult bindingResult) {
		this.checkError(bindingResult);
		Result result = userService.login(userLoginAO.getMobile(), userLoginAO.getPassword());
		return result;
	}
	
	@ApiOperation("发送短信验证码")
    @PostMapping("/send/sms/code")
	public Result sendSmsCode(@Validated SmsCodeAO smsCodeAO, BindingResult bindingResult) {
		
		this.checkError(bindingResult);
		// 生成 key
		String key = CommonUtils.smsCodeKey(smsCodeAO.getMobile(), smsCodeAO.getSmsType());
		if(redisTemplate.hasKey(key)) {
			return ok("验证码已发送", redisTemplate.getExpire(key, TimeUnit.SECONDS));
		}
		// 生成验证码 code
		String code = Constants.IS_PROD ? CommonUtils.randomNumber(4) : "8888";
		Map<String, Object> params = new HashMap<>();
		params.put("code", code);
		// 调用发送短信服务，发送短信
		Result result = smsService.send(smsCodeAO.getMobile(), smsCodeAO.getSmsType(), params);
		if(result.isOk()) {
			redisTemplate.opsForValue().set(key, code, 10, TimeUnit.MINUTES);
			result.setData(10*60);
		}
		
		return result;
	}
	
	@ApiOperation("获取图片验证码")
    @GetMapping("/get/image/code")
	public String getImageCode(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		String code = CommonUtils.randomNumber(4);
		HttpSession sessoin = request.getSession();
		log.info("获取验证码时的sessoin ==================》  " + sessoin.getId());
		sessoin.setAttribute("imageCode", code);
//		String key = Constants.IMAGE_CODE.concat(mobile);
//		redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
		int w = 100;
		int h = 30;
		try(OutputStream os = response.getOutputStream()) {
			ImageVerifyCodeUtils.outputImage(w, h, os, code);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return code;
	}
	
	@ApiOperation("验证图片验证码")
    @PostMapping("/check/image/code")
	public Result checkImageCode(@Validated CheckImageCodeAO checkImageCodeAO, BindingResult bindingResult, HttpServletRequest request) {
		this.checkError(bindingResult);
//		String key = Constants.IMAGE_CODE.concat(checkImageCodeAO.getMobile());
//		Object obj = redisTemplate.opsForValue().get(key);
//		if(CommonUtils.isEmpty(obj)) {
//			return fail("图片验证码已失效，请重新获取。");
//		}
		HttpSession sessoin = request.getSession();
		log.info("验证验证码时的sessoin ==================》  " + sessoin.getId());
		String imageCode = (String) sessoin.getAttribute("imageCode");
		
		if(CommonUtils.isEmpty(imageCode)) {
			return fail("图片验证码已失效，请重新获取。");
		}
		
		if(!imageCode.equals(checkImageCodeAO.getImageCode())) {
			return fail("图片验证码错误。");
		}
		
		return ok();
	}
	
	@ApiOperation("用户重置(找回)密码")
    @PostMapping("/reset/password")
	public Result resetPassword(@Validated UserResetPasswordAO userResetPasswordAO, BindingResult bindingResult) {
		
		this.checkError(bindingResult);
		// 验证短信验证码
		this.checkSmsCode(userResetPasswordAO.getMobile(), userResetPasswordAO.getSmsCode(), SmsType.PASSWORD_RESET);
		
		userService.resetPassword(userResetPasswordAO.getMobile(), userResetPasswordAO.getNewPassword());
		
		return ok();
	}
	
}
